package com.zerox.controller;

import com.alibaba.fastjson.JSON;
import com.zerox.domain.TableVO;
import com.zerox.pojo.SysUser;
import com.zerox.service.SysUserService;
import org.apache.commons.lang.math.RandomUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.validation.BindingResult;
import org.springframework.validation.FieldError;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.validation.Valid;
import java.io.File;
import java.io.IOException;
import java.util.List;
import java.util.Map;

@Controller
@RequestMapping("/user")
public class UserController {

    @Autowired
    private SysUserService sysUserService;

    @GetMapping("/tolist")
    public String toList() {
        return "list";
    }

    @RequestMapping(value = "/find",produces = {"application/json;charset=utf-8"})
    @ResponseBody
    public String find(Integer id,Model model){
        SysUser sysUser = sysUserService.selectById(id);
        model.addAttribute("user",sysUser);
        return JSON.toJSONString(sysUser);
    }

    @GetMapping("/toadd")
    public String toAdd() {
        return "add";
    }

    // @RequestMapping(value = "/list",method = RequestMethod.GET)
    //    public String list(Model model, @RequestParam(value = "ids",required = false,defaultValue = "0") Integer id){
    @GetMapping(value = "/list", produces = {"application/json;charset=utf-8"})
    @ResponseBody
    public String list(Model model, Integer page, HttpServletResponse resp, Integer limit, String realName, Integer roleId) throws IOException {

        List<SysUser> list = sysUserService.list(page, limit, realName, roleId);

        int count = sysUserService.count(realName, roleId);

        TableVO tableVO = new TableVO(0, count, list, "");

        String json = JSON.toJSONString(tableVO);

        return json;
    }

    @GetMapping("/list2")
    public String list2(Map<String, Object> map, @RequestParam(value = "ids", required = false, defaultValue = "0") Integer id) {
        System.out.println(this);
        map.put("id", id);
        return "forward:/user/tolist";
    }

    @GetMapping("/list1")
    public ModelAndView list1(@RequestParam(value = "ids", required = false, defaultValue = "0") Integer id) {
        System.out.println(id);
        ModelAndView modelAndView = new ModelAndView();
        modelAndView.setViewName("list.jsp");
        modelAndView.addObject("id", id);
        return modelAndView;
    }

    // @RequestMapping(value = "/add",method = RequestMethod.POST)

    @GetMapping("/view/{userId}")
    public String view(Model model,@PathVariable("userId") Integer id){
       SysUser sysUser = sysUserService.selectById(id);
       model.addAttribute("sysUser",sysUser);
        return "view";
    }
    @GetMapping("/delete/{id}")
    @ResponseBody
    public String  delete(@PathVariable Integer id){
        int result = sysUserService.delete(id);
        return result>0 ? "1" : "0";
    }
    @GetMapping("/toupdate/{id}")
    public String toUpdate(Model model,@PathVariable Integer id){
        SysUser sysUser = sysUserService.selectById(id);
        model.addAttribute("sysUser",sysUser);
        return "update";
    }
    @PostMapping("/add")
    public String add(Model model, HttpServletRequest request, @Valid SysUser sysUser, BindingResult bindingResult, MultipartFile idPic) throws IOException {

        if (bindingResult.hasErrors()){
            // 获取到所有的错误
            List<FieldError> fieldErrors = bindingResult.getFieldErrors();
            for (FieldError fieldError : fieldErrors) {
                // account  fieldError.getField()
                // 错误信息  fieldError.getDefaultMessage()
                model.addAttribute(fieldError.getField()+"Error",fieldError.getDefaultMessage());
            }
            return "add";
        }
        if (idPic.getSize()>5000000){
            model.addAttribute("idPicError","文件超过2M不能上传");
            return "add";
        }

        //指定文件存储的目录
        String suffix = idPic.getOriginalFilename().substring(idPic.getOriginalFilename().lastIndexOf("."));

        if (".jpg.png".indexOf(suffix)==-1){
            model.addAttribute("idPicError","文件格式不正确，不能上传");
            return "add";
        }
        String path = request.getSession().getServletContext().getRealPath("statics/") + File.separator + "upload";
        String fileName = RandomUtils.nextInt(1000000)+"_pic"+suffix;
        File fileTo = new File(path+File.separator+fileName);
        //如果文件不存在就创建
        if (!fileTo.exists()){
            fileTo.mkdirs();
        }
        //将文件存储到指定位置
        idPic.transferTo(fileTo);


        sysUser.setIdpicpath(fileName);
        int result =sysUserService.add(sysUser);
        if (result>0){
            return "redirect:tolist";
        }
        model.addAttribute("errorMsg","修改失败");
        return "forward:toupdate/"+sysUser.getId();
    }
    @PostMapping("/update")
    public String update(Model model,@Valid SysUser sysUser,BindingResult bindingResult){
        if (bindingResult.hasErrors()){
            // 获取到所有的错误
            List<FieldError> fieldErrors = bindingResult.getFieldErrors();
            for (FieldError fieldError : fieldErrors) {
                // account  fieldError.getField()
                // 错误信息  fieldError.getDefaultMessage()
                model.addAttribute(fieldError.getField()+"Error",fieldError.getDefaultMessage());
            }
            return "update";
        }

        int result =sysUserService.update(sysUser);

        if (result>0){
            return "redirect:tolist";
        }
        model.addAttribute("errorMsg","新增失败");
        return "update";
    }
    @GetMapping("/accountExists")
    @ResponseBody
    public String accountExists(String account){
        SysUser sysUser = sysUserService.selectByAccount(account);
        if (sysUser==null){
            return "0";
        }
        return "1";
    }
}
